//
//  ScanViewController.m
//  Medicine
//
//  Created by Just-h on 16/5/25.
//  Copyright © 2016年 JUST-Hychen. All rights reserved.
//

#import "ScanViewController.h"

@interface ScanViewController ()
{
//    Reachability *_networkReach;
}
@end

@implementation ScanViewController

#pragma mark - view life circle  viewController生命周期方法
- (void)viewDidLoad
{
    [super viewDidLoad];
    [self init_View];
    [self init_backItem];
    
    if ([self respondsToSelector:@selector(setEdgesForExtendedLayout:)]) {
        
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    self.view.backgroundColor = [UIColor blackColor];
    
    //设置扫码后需要扫码图像
//    self.isNeedScanImage = YES;
}

- (void)viewWillAppear:(BOOL)animated{
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    [super viewWillAppear:animated];
    
}

- (void)viewWillDisappear:(BOOL)animated{
    [self.navigationController setNavigationBarHidden:NO animated:animated];
    [super viewWillDisappear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    [self drawBottomItems];
    [self drawTitle];
    [self.view bringSubviewToFront:_topTitle];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - custom methods  自定义方法
- (void)init_View{
    
    //创建参数对象
    LBXScanViewStyle *style = [[LBXScanViewStyle alloc]init];
    
    //矩形区域中心上移，默认中心点为屏幕中心点
    style.centerUpOffset = 44;
    
    //扫码框周围4个角的类型,设置为外挂式
    style.photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle_Outer;
    
    //扫码框周围4个角绘制的线条宽度
    style.photoframeLineW = 6;
    
    //扫码框周围4个角的宽度
    style.photoframeAngleW = 24;
    
    //扫码框周围4个角的高度
    style.photoframeAngleH = 24;
    
    // 是否需要显示边框
    style.isNeedShowRetangle = NO;
    
    //扫码框内 动画类型 - 网格
    style.anmiationStyle = LBXScanViewAnimationStyle_LineMove;
    
    //网格图片
    style.animationImage = [UIImage imageNamed:@"CodeScan.bundle/qrcode_scan_part_net"];
    
    // 只识别框内码
    self.isOpenInterestRect = YES;
    
    self.style = style;
}

- (void)init_backItem{
    [self.navigationItem setHidesBackButton:YES animated:YES];
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(5, 0, 40, 40);
    [backBtn setImage:[UIImage imageNamed:@"app_scanrd_back_n_ic"] forState:UIControlStateNormal];
    [backBtn setImage:[UIImage imageNamed:@"app_scanrd_back_p_ic"] forState:UIControlStateHighlighted];
    [backBtn addTarget:self action:@selector(backBtnDidClick:) forControlEvents: UIControlEventTouchUpInside];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc]initWithCustomView:backBtn];
    self.navigationItem.leftBarButtonItem = backItem;
}

- (void)backBtnDidClick:(UIButton *)btn{
    if (self.presentingViewController) {
        [self dismissViewControllerAnimated:YES completion:nil];
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

//绘制扫描区域
- (void)drawTitle
{
    if (!_topTitle)
    {
        self.topTitle = [[UILabel alloc]init];
        _topTitle.bounds = CGRectMake(0, 0, 145, 60);
        _topTitle.center = CGPointMake(CGRectGetWidth(self.view.frame)/2, 50);
        
        //3.5inch iphone
        if ([UIScreen mainScreen].bounds.size.height <= 568 )
        {
            _topTitle.center = CGPointMake(CGRectGetWidth(self.view.frame)/2, 38);
            _topTitle.font = [UIFont systemFontOfSize:14];
        }
        
        
        _topTitle.textAlignment = NSTextAlignmentCenter;
        _topTitle.numberOfLines = 0;
        _topTitle.text = @"将取景框对准二维码即可自动扫描";
        _topTitle.textColor = [UIColor whiteColor];
        [self.view addSubview:_topTitle];
    }
}

// 相机初始化结束时调用
- (void)cameraInitOver
{

}

#pragma mark 底部功能View
- (void)drawBottomItems
{
    if (_bottomItemsView) {
        
        return;
    }
    
    self.bottomItemsView = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.view.frame)-164,
                                                                   CGRectGetWidth(self.view.frame), 100)];
    _bottomItemsView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.6];
    
    [self.view addSubview:_bottomItemsView];
    
    CGSize size = CGSizeMake(65, 87);
    self.btnFlash = [[UIButton alloc]init];
    _btnFlash.bounds = CGRectMake(0, 0, size.width, size.height);
    _btnFlash.center = CGPointMake(CGRectGetWidth(_bottomItemsView.frame)/3.0, CGRectGetHeight(_bottomItemsView.frame)/2);
    [_btnFlash setImage:[UIImage imageNamed:@"CodeScan.bundle/qrcode_scan_btn_flash_nor"] forState:UIControlStateNormal];
    [_btnFlash addTarget:self action:@selector(openOrCloseFlash) forControlEvents:UIControlEventTouchUpInside];
    
    self.btnPhoto = [[UIButton alloc]init];
    _btnPhoto.bounds = _btnFlash.bounds;
    _btnPhoto.center = CGPointMake(CGRectGetWidth(_bottomItemsView.frame)*2/3.0, CGRectGetHeight(_bottomItemsView.frame)/2);
    [_btnPhoto setImage:[UIImage imageNamed:@"CodeScan.bundle/qrcode_scan_btn_photo_nor"] forState:UIControlStateNormal];
    [_btnPhoto setImage:[UIImage imageNamed:@"CodeScan.bundle/qrcode_scan_btn_photo_down"] forState:UIControlStateHighlighted];
    [_btnPhoto addTarget:self action:@selector(openPhoto) forControlEvents:UIControlEventTouchUpInside];
    
    [_bottomItemsView addSubview:_btnFlash];
    [_bottomItemsView addSubview:_btnPhoto];
    
}


- (void)showError:(NSString*)str
{
    [UIAlertView bk_showAlertViewWithTitle:@"提示" message:@"需要开启相机权限才能拍摄照片哦" cancelButtonTitle:@"取消" otherButtonTitles:@[@"去开启"] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
        if (buttonIndex == 1) {
            NSURL *settingURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            if ([[UIApplication sharedApplication] canOpenURL:settingURL]) {
                [[UIApplication sharedApplication] openURL:settingURL];
            }
        }
    }];
}



- (void)scanResultWithArray:(NSArray<LBXScanResult*>*)array
{
    if (array.count < 1)
    {
        [self popAlertMsgWithScanResult:nil];
        
        return;
    }
    
    //经测试，可以同时识别2个二维码，不能同时识别二维码和条形码
    for (LBXScanResult *result in array) {
        
        NSLog(@"scanResult:%@",result.strScanned);
    }
    
    LBXScanResult *scanResult = array[0];
    
    NSString*strResult = scanResult.strScanned;
    
    // 扫描的图片
    self.scanImage = scanResult.imgScanned;
    
    if (!strResult) {
        
        [self popAlertMsgWithScanResult:nil];
        
        return;
    }
    
    //震动提醒
    // [LBXScanWrapper systemVibrate];
    //声音提醒
    // [LBXScanWrapper systemSound];
    
    [self showNextVCWithScanResult:scanResult];
    
}

- (void)popAlertMsgWithScanResult:(NSString*)strResult
{
    if (!strResult) {
        
        strResult = @"识别失败";
    }
    
    __weak __typeof(self) weakSelf = self;
    [LBXAlertAction showAlertWithTitle:@"扫码内容" msg:strResult chooseBlock:^(NSInteger buttonIdx) {
        //点击完，继续扫码
        [weakSelf reStartDevice];
    } buttonsStatement:@"知道了",nil];
}

#pragma mark 识别成功跳转
- (void)showNextVCWithScanResult:(LBXScanResult*)strResult
{
    [self.scanObj stopScan];
    
    if (self.BlockSuccessPopBack) {
        self.BlockSuccessPopBack(strResult.strScanned);
        [self.navigationController popViewControllerAnimated:YES];
        return;
    }
    if (strResult.strScanned.length>4 && [[strResult.strScanned substringToIndex:4] isEqualToString:@"www."]) {
        strResult.strScanned = [NSString stringWithFormat:@"http://%@",strResult.strScanned];
    }
    if ([CheckUtility checkForWebUrlWithData:strResult.strScanned]) {
        //跳转Url
        [JumpTool gotoWebVcWithUrl:strResult.strScanned viewController:self];
    }
    else {
        Show_Msg_Error(@"识别失败")
        [self performSelector:@selector(startScan) withObject:nil afterDelay:1.5];
    }
    
    //orderid=xxx&productid=xxx&sign=****
//    if ([strResult.strScanned containsString:@"orderid="] && [strResult.strScanned containsString:@"productid="] && [strResult.strScanned containsString:@"sign="]) {
//        [self loadScanCodeDataWiwhString:strResult.strScanned];
//    }else{
//        Show_Msg_Error(@"二维码错误，请重新扫描")
//        [self performSelector:@selector(startScan) withObject:nil afterDelay:1.5];
//    }
}

//- (void)loadScanCodeDataWiwhString:(NSString *)string{
//    NSRange range1 = [string rangeOfString:@"orderid="];
//    NSRange range2 = [string rangeOfString:@"&productid="];
//    NSRange range3 = NSMakeRange(range1.location+ range1.length,range2.location- range1.location- range1.length);
//    NSString *orderId = [string substringWithRange:range3];
//    WeakSelf_bb
//    [BusHttpRequest checkTicketDataWithParams:@[string,orderId] success:^(id object) {
//        CheckModel *model = [CheckModel mj_objectWithKeyValues:object];
//        [weakSelf gotoScanResultVc:model];
//        Dismiss_NoMsg
//    } failure:^(NSString *code, NSString *msg) {
//
//    }];
//}

//- (void)gotoScanResultVc:(CheckModel *)model{
//    ScanResultViewController *vc = [ScanResultViewController new];
//    vc.model = model;
//    [self.navigationController pushViewController:vc animated:YES];
//}

#pragma mark - 底部功能操作
//打开相册
- (void)openPhoto
{
    if ([LBXScanWrapper isGetPhotoPermission]){
        [self openLocalPhoto];
    }
    else
    {
        [self showError:@"      请到设置->隐私中开启本程序相册权限     "];
    }
}

//开关闪光灯
- (void)openOrCloseFlash
{
    
    [super openOrCloseFlash];
    
    
    if (self.isOpenFlash)
    {
        [_btnFlash setImage:[UIImage imageNamed:@"CodeScan.bundle/qrcode_scan_btn_flash_down"] forState:UIControlStateNormal];
    }
    else
        [_btnFlash setImage:[UIImage imageNamed:@"CodeScan.bundle/qrcode_scan_btn_flash_nor"] forState:UIControlStateNormal];
}

#pragma mark - 通知回调


#pragma mark - sources and delegates 代理、协议方法


#pragma mark - getters and setters 属性的设置和获取方法


@end
